let Koa = require('koa')
let views = require('koa-views')
let Router = require('koa-router')
let DB = require('./database/index')
let {resolve} = require('path')
let ejs = require('koa-ejs')
let static = require('koa-static')
let bodyParser = require('koa-bodyparser')


let app = new Koa()
let router = new Router()
app.listen(3000)

app.use(views(resolve(__dirname, './template'), {
    extension: 'ejs'
}))

app.use(static(resolve(__dirname, './static')))
app.use(bodyParser())
app.use(router.routes())


router.get('/', async (ctx, next) => {
    console.time('start')
    let data = await DB.find('users', {})
    await ctx.render('1.ejs', {data: data})
    console.timeEnd('start')
})

router.get('/find', async (ctx, next) => {
    console.time('start1')
    let {name, age} = ctx.request.query
    let data = await DB.find('users', {'name': name})
    ctx.body = data
    console.timeEnd('start1')
})

router.get('/template', async(ctx, next) => {
    console.time('start2')
    let data = await DB.find('users', {})
    await ctx.render('1.ejs', {data: data})
    console.timeEnd('start2')
})

router.get('/1.html', async (ctx, next) => {
    ctx.render('static/1.html')
})

// router.get('/update', async (ctx, next) => {
//     let {name, age} = ctx.request.query
//     DB.update('users', {"name"})
// })

router.get('/add', async (ctx, next) => {
    await ctx.render('add.ejs')
})

router.post('/insert', async (ctx, next) => {
    let res = await DB.insert('users', ctx.request.body)
    try {
        if (res.result.ok) {
            ctx.redirect('/')
        }
    } catch(err) {
        console.log(err)
        ctx.redirect('/add')
    }
})

router.get('/del', async (ctx, next) => {
    await ctx.render('del.ejs')
})

router.get('/delete', async (ctx, next) => {
    let data = await DB.remove('users', ctx.request.query)
    try {
        if (data.result.ok) {
            console.log('删除成功')
            ctx.redirect('/')
        }
    } catch (err) {
        console.log(err)
        ctx.redirect('/del')
    }
}) 

router.get('/up', async (ctx, next) => {
    await ctx.render('update.ejs')
})

router.post('/update', async (ctx, next) => {
    let {changeName, name, age} = ctx.request.body
    let data = await DB.update('users', {"name": changeName}, {"name": name, "age": age})
    try {
        if (data.result.ok) {
            ctx.redirect('/')
        }
    } catch (err) {
        console.log(err)
    }
})